package com.gzsxy.esjy.service.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.multipart.DiskFileUpload;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 转发包（暂无用）
 * @author zhangxiaolong
 * @date 2022/7/11 9:36
 */
public class TransChannelHandler extends SimpleChannelInboundHandler<HttpObject> {

	private final Logger log = LoggerFactory.getLogger(TransChannelHandler.class) ;
	private Channel channel;
	
	private final String tag ; 
	
	private DiskFileUpload fileUpload = null ;
	
	private long total ;

	public void setChannel(Channel channel) {
		this.channel = channel;
	}

	public String getTag() {
		return tag;
	}

	public DiskFileUpload getFileUpload() {
		return fileUpload;
	}

	public TransChannelHandler(String tag, Channel channel) {
		super();
		this.channel = channel;
		this.tag = tag ;
	}
	
	/**
	 * 复写方法，取消自动释放，留给代理通道释放
	 */
	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (acceptInboundMessage(msg)) {
            HttpObject imsg = (HttpObject) msg;
            channelRead0(ctx, imsg);
        } else {
            ctx.fireChannelRead(msg);
        }
    }
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
		channel.writeAndFlush(msg);
	}

	/**
	 * 处理内容
	 * @param msg
	 * @throws IOException
	 */
	private void doContent(HttpObject msg) throws IOException {
		if(msg instanceof HttpContent) {
			ByteBuf content = ((HttpContent) msg).content();
			if(fileUpload != null) {
				long lentgh  = fileUpload.length()+content.readableBytes();
				fileUpload.addContent(content,(lentgh==total));
			}else {
				channel.writeAndFlush(msg);
			}
		}
	}
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent)evt;
            if(idleStateEvent.state() == IdleState.ALL_IDLE) {
            	log.info("远程服务{} 连接通道{} 长期处于空闲状态,自动关闭",tag,ctx.channel().toString());
            	ctx.channel().close();
            }
        }
	}
	
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		log.info("重定向至服务{} ", tag);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		log.info("退出服务{} ", tag);
	}
	
//	@Override
//	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//		super.channelReadComplete(ctx);
//	}
//	@Override
//	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//		super.exceptionCaught(ctx, cause);
//	}
	
}
